package com.weiya.controller;

import com.google.code.kaptcha.Constants;
import com.weiya.entity.Permission;
import com.weiya.entity.User;
import com.weiya.response.ResponseCode;
import com.weiya.response.ResponseUtil;
import com.weiya.response.ResponseVo;
import com.weiya.response.SystemConst;
import com.weiya.service.PermissionService;
import com.weiya.service.UserService;
import com.weiya.system.shiro.PasswordHelper;
import com.weiya.util.UUIDUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p class="detail">
 * 功能:登录注册
 * </p>
 *
 * @author BaoWeiwei
 * @ClassName System controller.
 * @Version V1.0.
 * @date 2018.07.16 16:27:35
 */
@Controller
public class SystemController {

    private static Logger logger = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;


    /**
     * <p class="detail">
     * 功能:跳转到注册页
     * </p>
     *
     * @return string
     * @author BaoWeiwei
     * @date 2018.07.16 16:28:13
     */
    @GetMapping(value = "/register")
    public String register(){
        return "system/register";
    }


    /**
     * <p class="detail">
     * 功能:注册用户
     * </p>
     *
     * @param request         :
     * @param registerUser    :
     * @param confirmPassword :
     * @param verification    :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.17 22:23:35
     */
    @PostMapping(value = "/register")
    @ResponseBody
    public ResponseVo register(HttpServletRequest request, User registerUser,
                               String confirmPassword, String verification){
        //判断验证码
        String right_code = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isNotBlank(verification) && StringUtils.isNotBlank(right_code) && verification.equals(right_code)) {
            //验证码通过
        } else {
            return ResponseUtil.error(ResponseCode.VERIFY_CAPTCHA_ERROR.getCode(),ResponseCode.VERIFY_CAPTCHA_ERROR.getMsg());
        }
        String username = registerUser.getUsername();
        User user = userService.selectByUsername(username);
        if (null != user) {
            return ResponseUtil.error(ResponseCode.USERNAME_ALREADY_EXIST.getCode(),ResponseCode.USERNAME_ALREADY_EXIST.getMsg());
        }
        String password = registerUser.getPassword();
        //判断两次输入密码是否相等
        if (confirmPassword != null && password != null) {
            if (!confirmPassword.equals(password)) {
                return ResponseUtil.error(ResponseCode.PASSWPRD_DIFFERENT.getCode(),ResponseCode.PASSWPRD_DIFFERENT.getMsg());
            }
        }
        registerUser.setUserId(UUIDUtil.getUniqueIdByUUId());
        registerUser.setStatus(SystemConst.DATA_VALID);
        Date date = new Date();
        registerUser.setCreateTime(date);
        registerUser.setUpdateTime(date);
        registerUser.setLastLoginTime(date);
        registerUser = PasswordHelper.encryptPassword(registerUser);
        //注册
        int registerResult = userService.register(registerUser);
        if(registerResult > 0){
            return ResponseUtil.success("注册成功");
        }else {
            return ResponseUtil.error(ResponseCode.REGISTER_FAIL.getCode(),ResponseCode.REGISTER_FAIL.getMsg());
        }
    }

    /**
     * <p class="detail">
     * 功能:跳转登录页
     * </p>
     *
     * @return string
     * @author BaoWeiwei
     * @date 2018.07.16 16:28:13
     */
    @GetMapping("/login")
    public String login(){
        return "system/login";
    }


    @PostMapping("/login")
    @ResponseBody
    public ResponseVo login(HttpServletRequest request, User user, String verification,
                        @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe){
        //判断验证码
        String rightCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isNotBlank(verification) && StringUtils.isNotBlank(rightCode) && verification.equals(rightCode)) {
            //验证码通过
        } else {
            return ResponseUtil.error(ResponseCode.VERIFY_CAPTCHA_ERROR.getCode(),ResponseCode.VERIFY_CAPTCHA_ERROR.getMsg());
        }
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try{
            token.setRememberMe(1 == rememberMe);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (LockedAccountException e) {
            token.clear();
            return ResponseUtil.error(ResponseCode.LOCKED_ACCOUNT.getCode(),ResponseCode.LOCKED_ACCOUNT.getMsg());
        } catch (AuthenticationException e) {
            token.clear();
            return ResponseUtil.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR.getCode(),ResponseCode.USERNAME_OR_PASSWORD_ERROR.getMsg());
        }
        //更新最后登录时间
        userService.updateLastLoginTime((User) SecurityUtils.getSubject().getPrincipal());
        return ResponseUtil.success("登录成功！");
    }


    /**
     * <p class="detail">
     * 功能:根据用户id查询当前用户拥有的菜单权限
     * </p>
     *
     * @return list
     * @author BaoWeiwei
     * @date 2018.07.22 12:59:11
     */
    @PostMapping("/menu")
    @ResponseBody
    public List<Permission> getMenus(){
        String userId = ((User)SecurityUtils.getSubject().getPrincipal()).getUserId();
        List<Permission> permissionListList = permissionService.selectMenuByUserId(userId);
        return permissionListList;
    }


}
